import type { PayloadAction } from '@reduxjs/toolkit';
import { createSlice } from '@reduxjs/toolkit';

export type TopicOption = { id: string; value: string; value_cn: string; prompt: string };
export interface Question {
  id: string;
  topic: string;
  topic_cn: string;
  option: Array<TopicOption>;
}
export interface QuestionState {
  questionList: Array<Question>;
  selectedOption: {
    [key: string]: string;
  };
  promptMap: {
    [k: string]: string;
  };
}

const initialState: QuestionState = {
  questionList: [],
  selectedOption: {},
  promptMap: {},
};

export const questionSlice = createSlice({
  name: 'question',
  initialState,
  reducers: {
    setQuestionList: (state, action: PayloadAction<Array<Question>>) => {
      state.questionList = action.payload;
    },
    clearSelectedOption: (state) => {
      state.selectedOption = {};
    },
    addSelectedOption: (state, action: PayloadAction<{ qId: string; aId: string }>) => {
      const { qId, aId } = action.payload;
      state.selectedOption[qId] = aId;
    },
    setPromptMap: (state, action) => {
      state.promptMap = action.payload;
    },
  },
});

export const { setQuestionList, clearSelectedOption, addSelectedOption, setPromptMap } =
  questionSlice.actions;

export default questionSlice.reducer;
